use Archive::Zip qw( :ERROR_CODES :CONSTANTS );
use strict;

my $release_folder = 'release';
unless (-e $release_folder) {
	mkdir $release_folder;
}

my @t = gmtime;
my $date = sprintf('%04d%02d%02d', $t[5]+1900, $t[4]+1, $t[3]);

#
# release package
#

my $release = Archive::Zip->new();

# take the dll from plugin/Release
$release->addFile('plugin\\Release\\PlPN.dll', 'PlPN.dll');

# take the chm from doc
$release->addFile('doc\\PlPN.chm', 'PlPN.chm');

# take the entire contents of module
$release->addFolder('module', 1);

$release->compressAll(COMPRESSION_DEFLATED, 9);

unless ($release->writeToFileNamed("$release_folder/PlPN-$date.zip") == AZ_OK) {
	die "Unable to write zip file";
}

#
# doc package
#

my $doc = Archive::Zip->new();

# take the entire contents of doc/html
$doc->addFolder('doc/html', 1);

$doc->compressAll(COMPRESSION_DEFLATED, 9);

unless ($doc->writeToFileNamed("$release_folder/PlPN-htmldocs-$date.zip") == AZ_OK) {
	die "Unable to write zip file";
}

#
# scripts package
#

my $scripts = Archive::Zip->new();

# take the entire contents of scripts

# take the entire contents of doc/html
$scripts->addFolder('scripts', 1);

$scripts->compressAll(COMPRESSION_DEFLATED, 9);

unless ($scripts->writeToFileNamed("$release_folder/PlPN-scripts-$date.zip") == AZ_OK) {
	die "Unable to write zip file";
}

#
# helper subs
#

sub harvest {
	my ($folder, $recurse) = @_;
	
	opendir DIR, $folder or die "Unable to read folder '$folder': $!";
	my @e = readdir DIR;
	closedir DIR;
	
	my @ret;
	for my $e (@e) {
		next unless $e=~/[^.]/;	# skip . and ..
		if (-d "$folder/$e") {
			if ($recurse) {
				push @ret, harvest("$folder/$e", $recurse);
			}
		}
		else {
			push @ret, "$folder/$e";
		}
	}
	return @ret;
}

sub Archive::Zip::addFolder {
	my ($self, $folder, $recurse) = @_;
	$folder=~s:/$::;	# strip trailing slash
	my @files = harvest($folder, $recurse);
	
	for my $file (@files) {
		(my $in = $file)=~s:/:\\:g;
		(my $out = $file)=~s:^$folder/::g;
		$self->addFile($in, $out);
	}
}

sub Archive::Zip::compressAll {
	my ($self, $method, $level) = @_;
	for my $member ($self->members) {
		$member->desiredCompressionMethod($method);
		if ($method == COMPRESSION_DEFLATED and defined $level) {
			$member->desiredCompressionLevel($level);
		}
	}
}

__END__



my @html_files = harvest('doc/html', 1);	# 1 to recurse
for my $file (@html_files) {
	(my $in = $file)=~s:/:\\:g;
	(my $out = $file)=~s:^doc/html/::g;
	$doc->addFile($in, $out);
}

for my $member ($doc->members) {
	$member->desiredCompressionMethod(COMPRESSION_DEFLATED);
	$member->desiredCompressionLevel(9);
}


  - Generates a basic package (plugin/module/chm)
  - Generates an HTML docs package (html files from docs)
  - Generates a sample scripts package
